package org.brisling.base.service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ExportExcelDomain;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.util.PermissionCheck;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.exception.DangerousOperatorException;
import org.brisling.common.util.DateUtil;
import org.brisling.common.util.ExportUtil;
import org.brisling.common.util.JsonUtil;
import org.brisling.common.util.LongUtil;
import org.brisling.common.util.WhereUtil;
import org.brisling.sysman.domain.Department;
import org.brisling.sysman.domain.Users;
import org.brisling.workflow.domain.VOHistoric;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * 自定义查询基类，需要实现自定义查询方法的业务可继承该方法
 * @author : jackson wang
 * @Date   : 2015年6月8日 下午9:47:33
 * @version: 1.0
 * @param <Object> 泛型需定义的业务类实体，一般非<code>Entity</code>对象
 */
public abstract class AbstractBaseQueryService<T> extends AbstractBaseService{

	
	//定义起始页是否为1
	protected Boolean pageBasedOne=false;
	
	protected Class<T> clazz;
	
	private static Logger logger = LoggerFactory.getLogger(AbstractBaseQueryService.class);
	
	protected String tableName;
	
	protected HashMap<String,String> typeMap =new HashMap<String,String>();
	
	protected LinkedHashMap<String,String> orderMap =new LinkedHashMap<String,String>();
	
	protected String DEFAULT_ORDER_CORSE = "ORDER BY sortedid";
	protected String STWO_SQL = "SELECT %1$s FROM %2$s WHERE %3$s ORDER BY %4$s";
	
	protected String TWO_SQL = "SELECT * FROM %1$s WHERE %2$s ORDER BY %3$s";
	
	protected String TW_SQL = "SELECT * FROM %1$s WHERE %2$s ";
	
	protected String TO_SQL = "SELECT * FROM %1$s ORDER BY %2$s";
	
	protected String T_SQL = "SELECT * FROM %1$s " ;
	
	protected String ONE_SQL = "SELECT * FROM %1$s WHERE %2$s";	
	
	
	protected Map<String,Method> _methodMap=null;
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	/**
	 * 分页数据查询
	 * @param page	页号
	 * @param rows	行数
	 * @param condition	条件
	 * @param sort	排序
	 * @return	分页查询数据结果集
	 */
	
	@SuppressWarnings("rawtypes")
	protected ListDomain<LinkedHashMap> getListDomain(int page,int rows,HashMap<String,Object> condition,HashMap<String,String> sort){		
		
		ListDomain<LinkedHashMap> listDomain = new ListDomain<LinkedHashMap>();
		
		List<LinkedHashMap> _usrList = getAllList(page,rows,condition,sort);		
		
		listDomain.setTotal((long) _usrList.size());
		listDomain.setRows(_usrList);
		
		return listDomain;
		
	}
	
	
	protected ListDomain<T> getListDomainByConditionAndOrder(String body,Map<String,String> typeMap,LinkedHashMap<String,String> orderMap,Boolean alwaysExecute){		
		
		Map<String,Object> map =getBodyParam(body);			
			
		return getListDomainByConditionAndOrder(null,map,typeMap,orderMap,alwaysExecute,true);
		
	}
	
	/**
	 * 根据传入的sql语句与查询条件进行查询
	 * @param sql
	 * @param body
	 * @param typeMap
	 * @param orderMap
	 * @param alwaysExecute
	 * @return
	 */
	protected ListDomain<T> getListDomainByConditionAndOrder(String sql,String body,Map<String,String> typeMap,LinkedHashMap<String,String> orderMap,Boolean alwaysExecute){		
			
		Map<String,Object> map =getBodyParam(body);			
			
		return getListDomainByConditionAndOrder(sql,map,typeMap,orderMap,alwaysExecute,true);
		
	}
	
	protected ListDomain<T> getListDomainByConditionAndOrderUseTable(String body,Map<String,String> typeMap,LinkedHashMap<String,String> orderMap,Boolean alwaysExecute){		
		
		Map<String,Object> map =getBodyParam(body);			
			
		return getListDomainByConditionAndOrder(null,map,typeMap,orderMap,alwaysExecute,false);
		
	}
	
	/**
	 * 根据传入的sql语句与查询条件进行查询
	 * @param sql
	 * @param body
	 * @param typeMap
	 * @param orderMap
	 * @param alwaysExecute
	 * @return
	 */
	protected ListDomain<T> getListDomainByConditionAndOrderUseTable(String sql,String body,Map<String,String> typeMap,LinkedHashMap<String,String> orderMap,Boolean alwaysExecute){		
			
		Map<String,Object> map =getBodyParam(body);			
			
		return getListDomainByConditionAndOrder(sql,map,typeMap,orderMap,alwaysExecute,false);
		
	}
	

	/**
	 * 根据查询条件组合查询语句并执行查询
	 * @param sql				查询语句
	 * @param conditionMap		查询条件(condition,组合 and 查询;fuzzy,组合 or 查询)
	 * @param typeMap
	 * @param orderMap
	 * @param alwaysExecute
	 * @return
	 */
	
	protected ListDomain<T> getListDomainByConditionAndOrder(
			String sql,Map<String,Object> conditionMap,Map<String,String> typeMap,
			LinkedHashMap<String,String> orderMap,Boolean alwaysExecute){
		return this.getListDomainByConditionAndOrder(sql,conditionMap, typeMap, orderMap, alwaysExecute,true);
	}
	/**
	 * 根据查询条件组合查询语句并执行查询
	 * @param sql				查询语句
	 * @param conditionMap		查询条件(condition,组合 and 查询;fuzzy,组合 or 查询)
	 * @param typeMap
	 * @param orderMap
	 * @param alwaysExecute
	 * @return
	 */
	protected ListDomain<T> getListDomainByConditionAndOrder(
			String sql,Map<String,Object> conditionMap,Map<String,String> typeMap,
			LinkedHashMap<String,String> orderMap,Boolean alwaysExecute,Boolean useViewQuery){		
		
		Boolean _alwaysExe = false;
		
		_alwaysExe = alwaysExecute==null?false:alwaysExecute;
		
		String _sql = "";
		String whereCorse = null;		
		
		whereCorse = WhereUtil.getWhereCorse(conditionMap, typeMap);
				
		
		
		
		Boolean executeQry = false;
		
		//判断查询表名称
		String _table_name = useViewQuery?this.tableName:this.moduleName;
		
		if((whereCorse!=null)&&(whereCorse.trim().length()>0)){
			if((sql ==null )||(sql.trim().length()<=0))
				_sql = String.format(this.TW_SQL, _table_name,whereCorse);
			else
				_sql = String.format(sql, whereCorse);
			executeQry=true;
		}else{
			if((sql ==null )||(sql.trim().length()<=0))				
				_sql = String.format(this.T_SQL, _table_name);
			else
				_sql = String.format(sql, whereCorse);
		}
		
		String orderCorse = null;
		orderCorse = getOrderStr(orderMap);
		if(orderCorse!=null){
			_sql = _sql + " order by " +orderCorse;
		}
		Integer[] pageParam = LongUtil.getPageParam(conditionMap);
		if(_alwaysExe || executeQry){
			return getPagedListDomain(pageParam[0],pageParam[1],_sql);	
		}else{
			ListDomain<T> domain = new ListDomain<T>();
			domain.setTotal(0l);
			domain.setRows(new ArrayList<T>());
			return domain;
		}
		
	}
	
	/**
	 * 获取人员部门定义
	 * @param bodyMap
	 * @param usr
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected Map<String,Object> getDeptCondition(Map<String,Object> bodyMap,Users usr,String deptField){
		
		if(bodyMap!=null && bodyMap.containsKey(ConstSysParam.CONDITION_MAP_KEY)){
			Map<String,String> conditionMap = (Map<String, String>) bodyMap.get(ConstSysParam.CONDITION_MAP_KEY);
			
			if((usr!=null) && (deptField!=null && deptField.trim().length()>0)){
				if(usr.getManagedDept()!=null && (usr.getManagedDept().size()>0)){
					
					String deptids = null;
					List<Department> dept = usr.getManagedDept();
					
					for(int i=0;i<dept.size();i++){
						deptids = deptids==null?dept.get(i).getId().toString():deptids + ","+dept.get(i);
					}
					conditionMap.put(deptField+"_sql_in", deptids);
				}else{
					if(usr.getDeptid()!=null){
						String deptid = usr.getDeptid().toString();
						conditionMap.put(deptField, deptid);				
					}
				}				
			}						
		}
		return bodyMap;		
	}
	
	@SuppressWarnings("unchecked")
	protected List<T> getListByConditionAndOrder(String body,Map<String,String> typeMap,Map<String,String> orderMap,Boolean alwaysExecute){		
		
		if(body!=null){
			Map<String,Object> map =getBodyParam(body);			
			return getListByConditionAndOrder((Map<String, String>) map.get("condition"),typeMap,orderMap,alwaysExecute,true);
		}
		return null;
		
	}
	
	
	
	
	
	/**
	 * 获取当前可处理的业务流程
	 * @param sql
	 * @param conditionMap
	 * @return
	 */
	protected ListDomain<T> getUserTaskCanOperateListDomain(String userid,String sql,Map<String,Object> conditionMap){	
				
		
//		sql = String.format(sql, SysConfig.getUsr().getIdentify());
		Map<String,String> typeMap = this.getTypeMap(clazz);
		return this.getUserTaskCanOperateListDomain(userid,sql, conditionMap, typeMap);
	}
	/**
	 * 获取当前可处理的业务流程数据集合
	 * @param sql
	 * @param conditionMap
	 * @return
	 */
	
	protected ListDomain<T> getUserTaskCanOperateListDomain(String userid,String sql,Map<String,Object> conditionMap,Map<String,String> typeMap){	
				
		
//		sql = String.format(sql, SysConfig.getUsr().getIdentify());
		Map<String,String> _typeMap = null;
		_typeMap = (typeMap == null)||(typeMap.isEmpty())?this.getTypeMap(clazz):typeMap;
		Boolean _paged = checkPaged(conditionMap);
		
		String whereCorse = WhereUtil.getWhereCorse(conditionMap, _typeMap);
		whereCorse = (whereCorse==null)||(whereCorse.trim().length()<=0)?"":" where " + whereCorse;
		
		sql = String.format(sql,this.moduleName,getFlowUserId(userid),whereCorse);
		
		String orderCorse =  getOrderStr(orderMap);
		if(orderCorse!=null){
			sql = sql + " order by " +orderCorse;
		}
		
		if(_paged){
		Integer page = conditionMap.containsKey("page")?LongUtil.getIntValue(conditionMap.get("page").toString(),ConstSysParam.PAGE):ConstSysParam.PAGE;
		Integer pageSize = conditionMap.containsKey("rows")?LongUtil.getIntValue(conditionMap.get("rows").toString(),ConstSysParam.ROWS):ConstSysParam.ROWS;
		return this.getPagedListDomain(page, pageSize, sql)	;	
		}else{
			return this.abstractListDomain(sql);
		}
	}
	
	/**
	 * 获取当前已签收的业务流程
	 * @param sql
	 * @param conditionMap
	 * @return
	 */
	
	protected ListDomain<T> getUserSignedListDomain(String userid,String sql,Map<String,Object> conditionMap,Map<String,String> typeMap){	
				
		
//		sql = String.format(sql, SysConfig.getUsr().getIdentify());
		Map<String,String> _typeMap = null;
		_typeMap = (typeMap == null)||(typeMap.isEmpty())?this.getTypeMap(clazz):typeMap;
		Boolean _paged = checkPaged(conditionMap);
		
		String whereCorse = WhereUtil.getWhereCorse(conditionMap, _typeMap);
		whereCorse = (whereCorse==null)||(whereCorse.trim().length()<=0)?"":" where " + whereCorse;
		
		sql = String.format(sql,this.tableName,getFlowUserId(userid),whereCorse);
		if(_paged){
		Integer page = conditionMap.containsKey("page")?LongUtil.getIntValue(conditionMap.get("page").toString(),ConstSysParam.PAGE):ConstSysParam.PAGE;
		Integer pageSize = conditionMap.containsKey("rows")?LongUtil.getIntValue(conditionMap.get("rows").toString(),ConstSysParam.ROWS):ConstSysParam.ROWS;
		return this.getPagedListDomain(page, pageSize, sql)	;
		}else{
			return this.abstractListDomain(sql);
		}
	}
	
	/**
	 * 获取当前可查看的业务流程
	 * @param sql
	 * @param conditionMap
	 * @return
	 */
	
	protected ListDomain<T> getUserManagedListDomain(String sql,Map<String,Object> conditionMap,Map<String,String> typeMap){	
				
		
//		sql = String.format(sql, SysConfig.getUsr().getIdentify());
		Boolean _paged = checkPaged(conditionMap);
		
		Map<String,String> _typeMap = null;
		_typeMap = (typeMap == null)||(typeMap.isEmpty())?this.getTypeMap(clazz):typeMap;
		
		String whereCorse = WhereUtil.getWhereCorse(conditionMap, _typeMap);
		whereCorse = (whereCorse==null)||(whereCorse.trim().length()<=0)?"":" where " + whereCorse;
		
		sql = String.format(sql,this.tableName,whereCorse);
		
		String orderCorse =  getOrderStr(orderMap);
		if(orderCorse!=null){
			sql = sql + " order by " +orderCorse;
		}
		
		if(_paged){
		Integer page = conditionMap.containsKey("page")?LongUtil.getIntValue(conditionMap.get("page").toString(),ConstSysParam.PAGE):ConstSysParam.PAGE;
		Integer pageSize = conditionMap.containsKey("rows")?LongUtil.getIntValue(conditionMap.get("rows").toString(),ConstSysParam.ROWS):ConstSysParam.ROWS;
		return this.getPagedListDomain(page, pageSize, sql)	;	
		}else{
			return this.getSqlListDomain(sql);
		}
	}
	
	/**
	 * 判断是否分页
	 * @param conditionMap
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Boolean checkPaged(Map<String,Object> conditionMap){
		Boolean paged = true;
		if(conditionMap!=null){
			
			
			Object export = null;
			if(conditionMap.containsKey("exportAll")){
				export = conditionMap.get("exportAll");	
				if(export!=null){
					String ex = export.toString().trim();
					if(ex.compareTo("1")==0){
						paged = false;
					}
				}
			}else{
				if(conditionMap.containsKey(ConstSysParam.CONDITION_MAP_KEY)){
					Map<String,String> _paramMap = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
					if(_paramMap.containsKey("exportAll")){
						export = _paramMap.get("exportAll");	
						if(export!=null){
							String ex = export.toString().trim();
							if(ex.compareTo("1")==0){
								paged = false;
							}
						}
					}
				}
			}
		}
		
		return paged;
	}
	
	/**
	 * 获取当前未签收的业务流程
	 * @param sql
	 * @param conditionMap
	 * @return
	 */
	
	protected ListDomain<T> getUserUnsignedListDomain(String userid,String sql,Map<String,Object> conditionMap,Map<String,String> typeMap){	
				
		
//		sql = String.format(sql, SysConfig.getUsr().getIdentify());
		Map<String,String> _typeMap = null;
		Boolean _paged = checkPaged(conditionMap);
		_typeMap = (typeMap == null)||(typeMap.isEmpty())?this.getTypeMap(clazz):typeMap;
		
		String whereCorse = WhereUtil.getWhereCorse(conditionMap, _typeMap);
		whereCorse = (whereCorse==null)||(whereCorse.trim().length()<=0)?"":" where " + whereCorse;
		
		sql = String.format(sql,this.tableName,getFlowUserId(userid),whereCorse);
		if(_paged){
		Integer page = conditionMap.containsKey("page")?LongUtil.getIntValue(conditionMap.get("page").toString(),ConstSysParam.PAGE):ConstSysParam.PAGE;
		Integer pageSize = conditionMap.containsKey("rows")?LongUtil.getIntValue(conditionMap.get("rows").toString(),ConstSysParam.ROWS):ConstSysParam.ROWS;
		return this.getPagedListDomain(page, pageSize, sql)	;	
		}else{
			return this.abstractListDomain(sql);
		}
	}
	
	/**
	 * 获取当前用户已办结业务流程
	 * @param sql
	 * @param conditionMap
	 * @return
	 */
	public ListDomain<T> getUserFinishedListDomain(String sql,Map<String,Object> conditionMap,Map<String,String> typeMap){	
				
		
//		sql = String.format(sql, SysConfig.getUsr().getIdentify());
		Boolean _paged = checkPaged(conditionMap);
		Map<String,String> _typeMap = null;
		_typeMap = (typeMap == null)||(typeMap.isEmpty())?this.getTypeMap(clazz):typeMap;
		
		String whereCorse = WhereUtil.getWhereCorse(conditionMap, _typeMap);
		whereCorse = (whereCorse==null)||(whereCorse.trim().length()<=0)?"":" where " + whereCorse;
		sql = String.format(sql,this.moduleName,whereCorse);
		
		String orderCorse = null;
		orderCorse = getOrderStr(orderMap);
		if(orderCorse!=null){
			sql = sql + " order by " +orderCorse;
		}
		
		if(_paged){
		Integer page = conditionMap.containsKey("page")?LongUtil.getIntValue(conditionMap.get("page").toString(),ConstSysParam.PAGE):ConstSysParam.PAGE;
		Integer pageSize = conditionMap.containsKey("rows")?LongUtil.getIntValue(conditionMap.get("rows").toString(),ConstSysParam.ROWS):ConstSysParam.ROWS;
		return this.getPagedListDomain(page, pageSize, sql)	;	
		}else{
			return abstractListDomain(sql);
		}
	}
	
	/**
	 * 获取当前用户已办结业务流程
	 * @param sql
	 * @param conditionMap
	 * @return
	 */
	public ListDomain<T> getAllListDomain(String sql,Map<String,Object> conditionMap,Map<String,String> typeMap){	
				
		
//		sql = String.format(sql, SysConfig.getUsr().getIdentify());
		Boolean _paged = checkPaged(conditionMap);
		Map<String,String> _typeMap = null;
		_typeMap = (typeMap == null)||(typeMap.isEmpty())?this.getTypeMap(clazz):typeMap;
		
		String whereCorse = WhereUtil.getWhereCorse(conditionMap, _typeMap);
		whereCorse = (whereCorse==null)||(whereCorse.trim().length()<=0)?"":" where " + whereCorse;
		
		sql = String.format(sql,this.moduleName,whereCorse);
		
		String orderCorse = null;
		orderCorse = getOrderStr(orderMap);
		if(orderCorse!=null){
			sql = sql + " order by " +orderCorse;
		}
		
		if(_paged){
			Integer page = conditionMap.containsKey("page")?LongUtil.getIntValue(conditionMap.get("page").toString(),ConstSysParam.PAGE):ConstSysParam.PAGE;
			Integer pageSize = conditionMap.containsKey("rows")?LongUtil.getIntValue(conditionMap.get("rows").toString(),ConstSysParam.ROWS):ConstSysParam.ROWS;
			return this.getPagedListDomain(page, pageSize, sql)	;	
		}else{
			return abstractListDomain(sql);
		}
	}
	
	/**
	 * 获取当前业务模块已办结业务流程
	 * @param sql
	 * @param conditionMap
	 * @return
	 */
	protected ListDomain<T> getFinishedListDomain(String userid,String sql,Map<String,Object> conditionMap,Map<String,String> typeMap){	
				
		
//		sql = String.format(sql, SysConfig.getUsr().getIdentify());
		Map<String,String> _typeMap = null;
		_typeMap = (typeMap == null)||(typeMap.isEmpty())?this.getTypeMap(clazz):typeMap;
		
		String whereCorse = WhereUtil.getWhereCorse(conditionMap, _typeMap);
		whereCorse = (whereCorse==null)||(whereCorse.trim().length()<=0)?"":" where " + whereCorse;		
		
		sql = String.format(sql,this.tableName,getFlowUserId(userid),whereCorse);
		Integer page = conditionMap.containsKey("page")?LongUtil.getIntValue(conditionMap.get("page").toString(),ConstSysParam.PAGE):ConstSysParam.PAGE;
		Integer pageSize = conditionMap.containsKey("rows")?LongUtil.getIntValue(conditionMap.get("rows").toString(),ConstSysParam.ROWS):ConstSysParam.ROWS;
		return this.getPagedListDomain(page, pageSize, sql)	;	
	}
	
	/**
	 * 查询流程执行信息
	 * @param body	包含procInstId在内的参数信息
	 * @param sql
	 * @return
	 */
		
	protected ListDomain<Object> getHistoricByProcInstId(String body,String sql){
		Map<String,Object> conditionMap = this.getBodyParam(body);
		
		return getHistoricByProcInstId(conditionMap,sql);
	}
	/**
	 * 查询流程执行信息
	 * @param conditionMap	包含procInstId在内的参数信息
	 * @param sql
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected ListDomain<Object> getHistoricByProcInstId(Map<String,Object> conditionMap,String sql){
		
		String _key = "flowInstId";
		String procInstId = null;
		if(conditionMap!=null){
			if(conditionMap.containsKey(_key)){
				procInstId = conditionMap.get(_key).toString();
			}else{		
				Map<String,String> paramMap = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
				if(paramMap!=null && paramMap.containsKey(_key)){
					procInstId = paramMap.get(_key);
				}
			}
		
			if((procInstId!=null) && (procInstId.trim().length()>0)){
				
			
				sql=String.format(sql, procInstId);
			
				return this.getPagedClassListDomain(sql, conditionMap, VOHistoric.class, VOHistoric.class, true);
			}
		}
		return new ListDomain<Object>();
	}
	
	/**
	 * 根据conditionMap条件查询实体结果集
	 * @param conditionMap	条件参数集合
	 * @param typeMap		条件字段映射类型
	 * @param orderMap		排序字段定义
	 * @param alwaysExecute 条件为空是否执行查询
	 * @param pageable		是否分页
	 * @return
	 */
	protected List<T> getListByConditionAndOrder(Map<String,String> conditionMap,Map<String,String> typeMap,Map<String,String> orderMap,Boolean alwaysExecute,Boolean pageable){		
		
		Boolean _alwaysExe = false;
		Boolean _pageable=false;
		_alwaysExe = alwaysExecute==null?false:alwaysExecute;
		_pageable = _pageable==null?false:_pageable;
		String sql = "";			
		String whereCorse = WhereUtil.getConditionWhereCorse(conditionMap,typeMap);			
		
		Boolean executeQry = false;
		if(whereCorse!=null &&(whereCorse.trim().length()>0)){			
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
			executeQry=true;
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		
		String orderCorse = null;
		orderCorse = getOrderStr(orderMap);
		if(orderCorse!=null){
			sql = sql + " order by " +orderCorse;
		}
		
		Integer page =ConstSysParam.PAGE;
		Integer rows =ConstSysParam.ROWS;
		if(conditionMap!=null){
			page = conditionMap.containsKey("page")?LongUtil.getIntValue(conditionMap.get("page").toString(),null):page;	
			rows = conditionMap.containsKey("rows")?LongUtil.getIntValue(conditionMap.get("rows").toString(),null):rows;
		}
		
		if(_alwaysExe || executeQry){
			if(_pageable){
				return getPagedList(page,rows,sql);	
			}else
				return this.getAllList(sql);
		}else{
			
			return new ArrayList<T>();
		}
		
	}
	
	/**
	 * 根据conditionMap条件查询实体结果集
	 * @param sql			查询语句
	 * @param conditionMap	条件参数集合
	 * @param typeMap		条件字段映射类型
	 * @param orderMap		排序字段定义
	 * @param alwaysExecute 条件为空是否执行查询
	 * @param pageable		是否分页
	 * @return
	 */
	protected List<T> getListByConditionAndOrder(String sql,Map<String,String> conditionMap,Map<String,String> typeMap,Map<String,String> orderMap,Boolean alwaysExecute,Boolean pageable){		
		
		if((sql==null) || (sql.trim().length()<=0) ){
			return new ArrayList<T>();
		}
		Boolean _alwaysExe = false;
		Boolean _pageable=false;
		_alwaysExe = alwaysExecute==null?false:alwaysExecute;
		_pageable = _pageable==null?false:_pageable;
					
		String whereCorse = WhereUtil.getConditionWhereCorse(conditionMap,typeMap);			
		
		Boolean executeQry = false;
		if(whereCorse!=null &&(whereCorse.trim().length()>0)){			
			executeQry=true;
		}
		
		sql = String.format(sql,whereCorse);		
		
		String orderCorse = null;
		orderCorse = getOrderStr(orderMap);
		if(orderCorse!=null){
			sql = sql + " order by " +orderCorse;
		}
		
		Integer page =ConstSysParam.PAGE;
		Integer rows =ConstSysParam.ROWS;
		if(conditionMap!=null){
			page = conditionMap.containsKey("page")?LongUtil.getIntValue(conditionMap.get("page").toString(),null):page;	
			rows = conditionMap.containsKey("rows")?LongUtil.getIntValue(conditionMap.get("rows").toString(),null):rows;
		}
		
		if(_alwaysExe || executeQry){
			if(_pageable){
				return getPagedList(page,rows,sql);	
			}else
				return this.getAllList(sql);
		}else{
			
			return new ArrayList<T>();
		}
		
	}
	
	/**
	 * 根据body条件查询实体结果集
	 * @param sql	查询语句
	 * @param body	前端传入的条件参数
	 * @param clazz	条件匹配实体对象
	 * @param orderMap	排序字段
	 * @param alwaysExecute	条件为空时是否执行
	 * @return
	 */
	protected ListDomain<T> getListDomainByConditionAndOrder(String sql,String body,Class<?> clazz,LinkedHashMap<String,String> orderMap,Boolean alwaysExecute){		
		if(clazz!=null){
			HashMap<String,String> typeMap = this.getTypeMap(clazz);
			return this.getListDomainByConditionAndOrder(sql,body, typeMap, orderMap, alwaysExecute);
		}else{
			ListDomain<T> domain = new ListDomain<T>();
			domain.setRows(new ArrayList<T>());
			domain.setTotal(0l);
			return domain;
		}
	}
	/**
	 * 分页数据查询
	 * @param sql 查询语句
	 
	 * @return	分页查询数据结果集
	 * @throws DangerousOperatorException 
	 */	
	protected ListDomain<T> getSqlListDomain(String sql) {		
		
		ListDomain<T> listDomain = new ListDomain<T>();
		List<T> _usrList = null;
		Long count = this.getRowCount(sql);
		if(count!=null&&count>0){
			_usrList= getAllList(sql);
			listDomain.setRows(_usrList);
		}
		listDomain.setTotal(count);	
		
		return listDomain;
		
	}
	
	/**
	 * 分页数据查询
	 * @param sql 查询语句
	 
	 * @return	分页查询数据结果集
	 * @throws DangerousOperatorException 
	 */	
	protected ListDomain<T> abstractListDomain(String sql) {		
		
		ListDomain<T> listDomain = new ListDomain<T>();
		List<T> _usrList = null;
		Long count = this.getRowCount(sql);
		if(count!=null&&count>0){
			_usrList= getAllList(sql);
			listDomain.setRows(_usrList);
		}
		listDomain.setTotal(count);	
		
		return listDomain;
		
	}
	
	
	/**
	 * 查询获取指定类型结果集
	 * @param sql
	 * @param body
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings({ "rawtypes"})	
	protected ListDomain<Object> getPagedClassListDomain(String sql,String body,Class<?> clazz,Class<?> retClazz,Boolean alwaysExecute){		
		
		ListDomain<LinkedHashMap> domains = getPagedMapListDomain(sql,body,clazz,alwaysExecute);
		ListDomain<Object> odomain = new ListDomain<Object>();
		if(domains!=null){
			List<Object> lists =reflectObjectMaps(retClazz,domains.getRows());
			odomain.setTotal(domains.getTotal());
			odomain.setRows(lists);
		}else{
			odomain.setTotal(0l);
			odomain.setRows(new ArrayList<Object>());
		}
		return odomain;
		
	}
	
	/**
	 * 查询获取指定类型结果集
	 * @param sql
	 * @param body
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings({ "rawtypes"})	
	protected ListDomain<Object> getPagedClassListDomain(String sql,Map<String,Object> map,Class<?> clazz,Class<?> retClazz,Boolean alwaysExecute){		
		
		ListDomain<LinkedHashMap> domains = getPagedMapListDomain(sql,map,clazz,alwaysExecute);
		ListDomain<Object> odomain = new ListDomain<Object>();
		if(domains!=null){
			List<Object> lists =reflectObjectMaps(retClazz,domains.getRows());
			odomain.setTotal(domains.getTotal());
			odomain.setRows(lists);
		}else{
			odomain.setTotal(0l);
			odomain.setRows(new ArrayList<Object>());
		}
		return odomain;
		
	}
	
	/**
	 * 查询获取指定类型结果集
	 * @param sql
	 * @param body
	 * @param clazz
	 * @return
	 */	
	protected ListDomain<Object> getPagedClassListDomain(String body,Class<?> clazz,Class<?> retClazz,Boolean alwaysExecute){		
		
		return this.getPagedClassListDomain(null, body, clazz, retClazz, alwaysExecute);		
	}
	
	/**
	 * 查询窗口满意度数据
	 * @param body
	 * @return
	 */
	@SuppressWarnings({ "rawtypes" })	
	protected ListDomain<LinkedHashMap> getPagedMapListDomain(String sql,String body,Class<?> clazz,Boolean alwaysExecute){		
		
		Map<String,Object> map =getBodyParam(body);
		return this.getPagedMapListDomain(sql, map, clazz, alwaysExecute);
		
	}
	
	/**
	 * 查询窗口满意度数据
	 * @param body
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })	
	protected ListDomain<LinkedHashMap> getPagedMapListDomain(String sql,Map<String,Object> conditionMap,Class<?> clazz,Boolean alwaysExecute){		
		
		
		boolean _alwaysExecute = false;		
		_alwaysExecute= alwaysExecute==null?_alwaysExecute:alwaysExecute;
		
		HashMap<String,String> typeMap = this.getTypeMap(clazz);
		String whereCorse = null;
		Integer _page =ConstSysParam.PAGE;
		Integer _rows = ConstSysParam.ROWS;
		if(conditionMap!=null){
			if(conditionMap.containsKey("condition")){
				whereCorse = WhereUtil.getConditionWhereCorse((Map<String, String>) conditionMap.get("condition"), typeMap);
			}
			_page = conditionMap.containsKey("page")?LongUtil.getIntValue(conditionMap.get("page").toString(),ConstSysParam.PAGE):_page;
			_rows = conditionMap.containsKey("rows")?LongUtil.getIntValue(conditionMap.get("rows").toString(),ConstSysParam.ROWS):_rows;
		}
		
		if(whereCorse!=null && whereCorse.trim().length()>0){
			whereCorse = " where " +whereCorse;
			
			sql = String.format(sql,whereCorse);
			_alwaysExecute = true;
			
		}
		
		if(_alwaysExecute){						
			return getPagedListMapDomain(_page, _rows, sql);
		}else{
			ListDomain<LinkedHashMap> domains = new ListDomain<LinkedHashMap>();				
			domains.setRows(new ArrayList<LinkedHashMap>());
			domains.setTotal(0l);
			return domains;
		}
		
		
	}
	
	/**
	 * 分页数据查询
	 * @param page	页号
	 * @param pageSize	行数
	 * @param sql	查询语句
	 * @return	根据easyui前端列表所需格式封装的数据集
	 * @throws DangerousOperatorException 
	 */	
	protected <E>ListDomain<E> getPagedListDomain(Integer page,Integer pageSize,String sql,Class<E> clzE) {		
		
		
		List<E> reports = null;
		
		Long count = this.getRowCount(sql);
		ListDomain<E> listDomain = new ListDomain<E>();
		
		
		if(count!=null&&count>0){
			reports = this.reflectClassedtMaps(clzE, getPagedListMap(page,pageSize,sql));
			listDomain.setTotal(count);
			listDomain.setRows(reports);
		}else{
			listDomain.setTotal(0l);
			listDomain.setRows(new ArrayList<E>());
		}	
		
		return listDomain;			
	}
	
	/**
	 * 分页数据查询
	 * @param page	页号
	 * @param pageSize	行数
	 * @param sql	查询语句
	 * @return	根据easyui前端列表所需格式封装的数据集
	 * @throws DangerousOperatorException 
	 */	
	protected ListDomain<T> getPagedListDomain(Integer page,Integer pageSize,String sql) {		
		
		
		List<T> reports = null;
		
		Long count = this.getRowCount(sql);
		ListDomain<T> listDomain = new ListDomain<T>();
		
		
		if(count!=null&&count>0){
			reports = getPagedList(page,pageSize,sql);
			listDomain.setTotal(count);
			listDomain.setRows(reports);
		}else{
			listDomain.setTotal(0l);
			listDomain.setRows(new ArrayList<T>());
		}	
		
		return listDomain;			
	}
	
	/**
	 * 检查是否超级部门
	 * @param allDept
	 * @param subModuleAllDept
	 * @return
	 */
	protected boolean isSuperDept(String userid,String allDept,String subModuleAllDept){
		
		return PermissionCheck.getInstance().isSuperDept(userid, allDept, subModuleAllDept);
	}
	
	/**
	 * 检查是否超级部门
	 * @param allDept
	 * @param subModuleAllDept
	 * @return
	 */
	protected String getUserid(HttpSession session){
		
		if(session!=null){
			Object userid = session.getAttribute(ConstSysParam.SYS_USERID);
			if(userid!=null)
				return userid.toString();
			
		}
		return null;
	}
	
	/**
	 * 检查是否管理角色
	 * @param allDept
	 * @param subModuleAllDept
	 * @return
	 */
	protected boolean isManageJob(String userid){
		
		return PermissionCheck.getInstance().isManageJob(userid);
	}
	
	
	/**
	 * 检查是否业务管理部门
	 * @param userid	用户id
	 * @param fullBizcode	业务编码
	 * @return
	 */
	protected boolean isBizManageDept(String userid,String fullBizcode){
		
		return PermissionCheck.getInstance().isBizManageDept(userid,fullBizcode);
	}
	
	/**
	 * 获取用户管理的部门
	 * @return
	 */
	protected String getUserDeptids(String userid){
		Users usr =SysConfig.getUsr(userid);
		String deptids = null;
		if(usr!=null){
			
			if(usr.getManagedDept()!=null && usr.getManagedDept().size()>0){
				for (int i=0;i<usr.getManagedDept().size();i++){
					Long did = usr.getManagedDept().get(i).getId();
					deptids = deptids ==null?did.toString():deptids + ","+did;
				}
			}else{
				if(usr.getDeptid()!=null)
					deptids = usr.getDeptid().toString();
			}
		}
		
		return deptids;
	}
	
	/**
	 * 获取用户管理的部门
	 * @return
	 */
	protected String getJobDeptids(String userid){
		return PermissionCheck.getInstance().getJobDeptids(userid);
	}
	
	/**
	 * 获取用户管理的部门
	 * @return
	 */
	protected String getJobDeptidAndAccountDeptids(String userid){
		return PermissionCheck.getInstance().getJobDeptidAndAccountDeptids(userid);
	}
	
	/**
	 * 添加部门过滤条件到map中
	 * @param conditionMap
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected Map<String,Object> addDeptConditionToMap(String userid,Map<String,Object> conditionMap,String fieldName){
		String deptids = this.getUserDeptids(userid);
		String _filedName = fieldName==null?"doct_depart_code":fieldName;
		
		_filedName = _filedName+"_in";
		Map<String,String> paramMap = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
		if(paramMap==null)
			paramMap = new HashMap<String,String>();
		paramMap.put(_filedName, deptids);
		conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
		return conditionMap;
	}
	
	/**
	 * 添加部门过滤条件到map中
	 * @param conditionMap
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected Map<String,Object> addJobDeptConditionToMap(String userid,Map<String,Object> conditionMap,String fieldName){
		String deptids = this.getJobDeptids(userid);
		String _filedName = fieldName==null?"doct_depart_code":fieldName;
		
		_filedName = _filedName+"_in";
		Map<String,String> paramMap = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
		if(paramMap==null)
			paramMap = new HashMap<String,String>();
		paramMap.put(_filedName, deptids);
		conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
		return conditionMap;
	}
	
	
	
	/**
	 * 添加用户id到过滤条件
	 * @param userid		用户id
	 * @param conditionMap	条件map对象
	 * @param fieldName		用户字段名称
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected Map<String,Object> addUsridConditionToMap(String userid,Map<String,Object> conditionMap,String fieldName){
		
		String _filedName = fieldName==null?"userid":fieldName;
		
		_filedName = _filedName+"_in";
		Map<String,String> paramMap = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
		if(paramMap==null)
			paramMap = new HashMap<String,String>();
		paramMap.put(_filedName, userid);
		conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
		return conditionMap;
	}
	/**
	 * 分页数据查询
	 * @param page	页号
	 * @param pageSize	行数
	 * @param sql	查询语句
	 * @return	根据easyui前端列表所需格式封装的数据集
	 * @throws DangerousOperatorException 
	 */	
	@SuppressWarnings("rawtypes")
	protected ListDomain<LinkedHashMap> getPagedListMapDomain(Integer page,Integer pageSize,String sql) {		
		
		
		List<LinkedHashMap> reports = null;
		
		Long count = this.getRowCount(sql);
		ListDomain<LinkedHashMap> listDomain = new ListDomain<LinkedHashMap>();
		
		
		if(count!=null&&count>0){
			reports = getPagedListMap(page,pageSize,sql);
			listDomain.setTotal(count);
			listDomain.setRows(reports);
		}else{
			listDomain.setTotal(0l);
			listDomain.setRows(new ArrayList<LinkedHashMap>());
		}	
		
		return listDomain;			
	}
	
	
	
	
	
	/**
	 * 分页数据查询
	 * @param page	页号
	 * @param pageSize	行数
	 * @return	根据easyui前端列表所需格式封装的数据集
	 */
	
	@SuppressWarnings("rawtypes")
	protected ListDomain<LinkedHashMap> getPagedListDomain(Integer page,Integer pageSize){		
		
		
		List<LinkedHashMap> reports= getPagedList(page,pageSize);		
		
		ListDomain<LinkedHashMap> listDomain = new ListDomain<LinkedHashMap>();
		
		if((reports!=null)){			
			listDomain.setTotal((long) reports.size());
			listDomain.setRows(reports);
		}else{			
			listDomain.setTotal(0l);
			listDomain.setRows(new ArrayList<LinkedHashMap>());
		}		
		return listDomain;			
	}
	
	
	/**
	 * 查询并返回分页业务记录
	 * @param page	页号
	 * @param row	行数
	 * @param condition	条件
	 * @param sort	排序
	 * @return
	 */
	
	@SuppressWarnings("rawtypes")
	protected List<LinkedHashMap> getAllList(int page,int row ,HashMap<String,Object> condition,HashMap<String,String> sort ){
		String sql = String.format(this.T_SQL, tableName);
		
		 //建立有类型的查询  
        Query query= entityManager.createNativeQuery(sql);  
        		
		return this.getQueryResult(query);			
	}
	
	
	/**
	 * 查询并返回分页业务记录
	 * @param page	页号
	 * @param row	行数
	 * @param condition	条件
	 * @param sort	排序
	 * @return
	 * @throws DangerousOperatorException 
	 */
	
	
	protected List<T> getAllList(String sql )  {
		List<T> lists = null;
		try{
			lists =this.reflectMaps(clazz, getQueryResult(checkSqlDangerous(sql)));
		}catch(DangerousOperatorException e){
			logger.info("suspends dangerous operator !");
		}
		
		return lists;
	}
	
	
	
	@SuppressWarnings("rawtypes")
	protected List<LinkedHashMap> getMappedList(String sql )  {
		List<LinkedHashMap> lists = null;
		try {
			 lists= getQueryResult(checkSqlDangerous(sql));
		} catch (DangerousOperatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lists;
	}
	
	/**
	 * 获取单条记录
	 * @param sql
	 * @return
	 */	
	protected HashMap<String,String> getSingleRecord(String sql )  {
		HashMap<String,String> lists = null;
		try {
			 lists= getSingleResult(checkSqlDangerous(sql));
		} catch (DangerousOperatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lists;
	}
	
	/**
	 * 检查sql安全性并返回Query对象
	 * @param sql
	 * @return	
	 * @throws DangerousOperatorException
	 */
	protected Query checkSqlDangerous(String sql) throws DangerousOperatorException{
		if(sql!=null){
			String _sql = sql.toLowerCase();
			if((_sql.contains(" delete "))||(_sql.contains(" update "))){
				logger.info(" 该操作危及数据安全，已通知系统管理员进行处理 ！");
				throw new DangerousOperatorException();
			}
		}
		return entityManager.createNativeQuery(sql); 
	}
	
	
	/**
	 * 查询并返回分页业务记录
	 * @param page	页号
	 * @param row	行数
	 * @param condition	条件
	 * @param sort	排序
	 * @return
	 * @throws DangerousOperatorException 
	 */
	
	
	protected <E>List<E> getClassedAllList(String sql,Class<E> t ) throws DangerousOperatorException{
		
		        		
        List<E> lists = null;
		try{
			lists =this.reflectClassedtMaps(t, getQueryResult(checkSqlDangerous(sql)));
		}catch(DangerousOperatorException e){
			logger.info("suspends dangerous operator !");
		}
		
		return lists;		
	}
	
	
	/**
	 * 查询并返回所有业务记录
	 * @param repo 仓库类
	 * @return
	 */
	
	@SuppressWarnings("rawtypes")
	protected List<LinkedHashMap> getPagedList(String page,String pageSize){
		
		String sql = String.format(this.T_SQL, tableName);         
        
        //建立有类型的查询  
        Query query= entityManager.createNativeQuery(sql);  
        //另外有详细查询条件的在jpql中留出参数位置来(?1 ?2 ?3....)，然后在这设置  
        //reportTypedQuery.setParameter(1, params);        
		
		Integer[] pageParam = this.getPageParam(page, pageSize); 
		
		query.setFirstResult(pageParam[0]);
		query.setMaxResults(pageParam[1]);		
		
		return this.getQueryResult(query);	
			
	}	
	
	/**
	 * 查询并返回分页数据集
	 * @param page
	 * @param pageSize
	 * @param sql
	 * @return
	 * @throws DangerousOperatorException 
	 */	
	protected List<T> getPagedList(Integer page,Integer pageSize,String sql)   {       
		
		return this.reflectMaps(clazz, getPagedListMap(page,pageSize,sql));			
	}
	
	/**
	 * 查询并返回分页数据集
	 * @param page
	 * @param pageSize
	 * @param sql
	 * @return
	 * @throws DangerousOperatorException 
	 */	
	@SuppressWarnings("rawtypes")
	protected List<LinkedHashMap> getPagedListMap(Integer page,Integer pageSize,String sql)   {		       
        
        //建立有类型的查询  
		
        Query query = null;
		try {
			query = checkSqlDangerous(sql);
		} catch (DangerousOperatorException e) {
			// TODO Auto-generated catch block
			logger.debug("DangerousOperatorException throws !!!");
			return null;
		}  
		
        //另外有详细查询条件的在jpql中留出参数位置来(?1 ?2 ?3....)，然后在这设置  
        //reportTypedQuery.setParameter(1, params);        
		
		Integer[] pageParam = this.getPageParam(page, pageSize); 
		
		query.setFirstResult(pageParam[0]);
		query.setMaxResults(pageParam[1]);		
		
		return  getQueryResult(query);			
	}
	
	/**
	 * 查询记录总数
	 * @param sql
	 * @return	记录数量
	 */
	protected Long getRowCount(String sql)   {		       
        
        //建立有类型的查询  
		
        Query query = null;
        
        
        if(sql==null){
        	return null;
        }
        String countQry = String.format("SELECT COUNT(*) cnt FROM ( %1$s ) c", cutOrderCorse(sql));
		try {
			query = checkSqlDangerous(countQry);
		} catch (DangerousOperatorException e) {
			// TODO Auto-generated catch block
			logger.debug("DangerousOperatorException throws !!!");
			return null;
		}  
		
        //另外有详细查询条件的在jpql中留出参数位置来(?1 ?2 ?3....)，然后在这设置  
        //reportTypedQuery.setParameter(1, params);        
		BigDecimal counts =  null;
		
		Integer icnt = null;
		
		Object retObj = query.getSingleResult();
		try{
			counts = (BigDecimal)retObj;
		}catch(ClassCastException e){
			icnt = (Integer)retObj;
		}
		Long _cnt =counts==null?(icnt==null?0l:Long.valueOf(icnt)):counts.longValue();
		return 		_cnt;	
	}
	
	/*
	 * 去除统计sql里面的order by 排序内容 
	 * @param sql
	 * @return
	 */
	private String cutOrderCorse(String sql){
		if(sql==null){
			return null;
		}
		int _index = sql.indexOf("order by");
		String retSql = "";
        if(_index>=0){
        	
        	int _endIndex = sql.substring(_index,sql.length()).indexOf(")");
        	if(_endIndex>=0){
        		retSql = sql.substring(0, _index) + sql.substring(_index+_endIndex, sql.length());
        		if(retSql.indexOf("order by")>=0){
        			retSql = cutOrderCorse(retSql);
        		}
        	}else{
        		retSql = sql.substring(0, _index);
        	}
        }else{
        	retSql = sql;
        }
//        System.out.println("retSql: "+retSql);
        return retSql;
	}
	
	/**
	 * 获取业务数据统计信息
	 * @param body	条件参数
	 * @param sql	查询语句
	 * @param tableName	表名称
	 * @param typeClz	参数匹配类
	 * @return
	 */
	
	@SuppressWarnings("unchecked")
	public Long getBizCount(String body,String sql,String tableName,Class<?> typeClz){
		
		
		Map<String,Object> map = this.getBodyParam(body);
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		
		return  this.getBizCount(paramMap,sql,tableName,typeClz);
	}
	
	/**
	 * 获取业务数据统计信息
	 * @param paramMap	条件参数
	 * @param sql	查询语句
	 * @param tableName	表名称
	 * @param typeClz	参数匹配类
	 * @return
	 */
	
	public Long getBizCount(Map<String,String> paramMap,String sql,String tableName,Class<?> typeClz){
		
		Map<String,String> typeMap = typeClz==null?this.getTypeMap(clazz):this.getTypeMap(typeClz);
		
		String _tableName =(tableName==null)||(tableName.trim().length()<=0)?this.getTableName():tableName;
		String _sql = null;		
		
		String whereCorse = WhereUtil.getConditionWhereCorse(paramMap,typeMap );
		
		if((sql!=null)&& (sql.trim().length()>0) ){
			if((whereCorse !=null)&&(whereCorse.trim().length()>0)){
				sql = String.format(sql, " where " + whereCorse);
			}else{
				sql = String.format(sql, "");
			}
			
		}else{
			if((whereCorse !=null)&&(whereCorse.trim().length()>0)){
				_sql = sql==null?this.TW_SQL:sql;
				sql = String.format(_sql, _tableName,whereCorse);
			}else{
				_sql = sql==null?this.T_SQL:sql;
				sql = String.format(_sql, _tableName);
			}
		}
		
		return  this.getRowCount(sql);
	}
	
	/**
	 * 查询并返回分页数据集
	 * @param page
	 * @param pageSize
	 * @return
	 */
	
	@SuppressWarnings("rawtypes")
	protected List<LinkedHashMap> getPagedList(Integer page,Integer pageSize){		       
        
		String sql = String.format(T_SQL, this.tableName);
        //建立有类型的查询  
        Query query= entityManager.createNativeQuery(sql);  
        //另外有详细查询条件的在jpql中留出参数位置来(?1 ?2 ?3....)，然后在这设置  
        //reportTypedQuery.setParameter(1, params);        
		
		Integer[] pageParam = this.getPageParam(page, pageSize); 
		
		query.setFirstResult(pageParam[0]);
		query.setMaxResults(pageParam[1]);		
		
		return this.getQueryResult(query);			
	}
	
	
	
	/**
	 * 分页查询树结构数据集
	 * @param page
	 * @param pageSize
	 * @param id
	 * @return
	 */		
	protected List<T> getPagedTreeList(Long id){		       
        
        StringBuilder wsb = new StringBuilder();
        String whereCorse = "";
        
        if(id==null){        	
        	whereCorse = wsb.append("parentid is null").toString();        	
        }else{
        	whereCorse =String.format(wsb.append("parentid  = %1$d " ).toString(),id);        	
        }
		String sql = String.format(this.TWO_SQL, this.tableName,whereCorse,"sortedid");
				
        //建立有类型的查询  
		
		Query query= entityManager.createNativeQuery(sql); 
		@SuppressWarnings("rawtypes")
		List<LinkedHashMap>  maps = this.getQueryResult(query);
		
		List<T> lists = this.reflectMaps(clazz, maps);
		return lists;
		
	}
	
	/**
	 * 分页查询树结构数据集
	 * @param page
	 * @param pageSize
	 * @param id
	 * @return
	 */		
	protected List<T> getPagedCurrentTreeList(Long id){		       
        
        
        String _id = null;
        if(id!=null && id>0){
        	_id = id.toString();        	
        }
		return this.getTreeList(_id);
		
	}
	
	/**
	 * 分页查询树结构数据集	
	 * @param ids	节点id
	 * @return
	 */		
	protected List<T> getTreeList(String ids){		       
        
        StringBuilder wsb = new StringBuilder();
        String whereCorse = "";
        
        if(ids==null){
        	whereCorse = wsb.append("parentid is null").toString();
        	
        }else{
        	whereCorse =String.format(wsb.append("id  in( %1$s) " ).toString(),ids);        	
        }
		String sql = String.format(this.TWO_SQL, this.tableName,whereCorse,"sortedid");
				
        //建立有类型的查询  
		
		Query query= entityManager.createNativeQuery(sql); 
		return this.reflectMaps(clazz, this.getQueryResult(query));
		
	}
	/**
	 * 分页查询树结构数据集
	 * @param page
	 * @param pageSize
	 * @param id
	 * @return
	 */		
	protected ListDomain<T> getPagedTreeListDomain(Long id){		       
        
        StringBuilder wsb = new StringBuilder();
        String whereCorse = "";
        ListDomain<T> listDomain = new ListDomain<T>();
        if(id==null){
        	whereCorse = wsb.append("parentid is null").toString();
        	
        }else{
        	whereCorse =String.format(wsb.append("parentid  = %1$d " ).toString(),id);        	
        }
		String sql = String.format(this.TW_SQL, this.tableName,whereCorse);
				
        //建立有类型的查询  
		Long _cnt = this.getRowCount(sql);
		if(_cnt!=null&&_cnt>0){
			Query query= entityManager.createNativeQuery(sql); 
			listDomain.setRows(this.reflectMaps(clazz, this.getQueryResult(query)));
		}
		
		listDomain.setTotal(_cnt);
       	return 		listDomain;	
	}
	
	
	
	/**
	 * 查询单挑业务记录
	 * @param tid	业务唯一编码
	 * @param _repo	仓库类
	 * @return		业务对象实体类
	 */
	protected Object getOne(String tid) {
		
		Long _tid = LongUtil.getLongValue(tid, null);
		return this.getOne(_tid);
	}
	
	/**
	 * 查询单条业务记录
	 * @param viewName	表或视图名称
	 * @param tid		业务id值
	 * @param e			业务实体类
	 * @return
	 */
	protected <E>E getClassedOne(String viewName,String tid,Class<E> e) {
		
		Long _tid = LongUtil.getLongValue(tid, null);
		if(_tid==null){
			return null;
		}
		StringBuilder whereCorse = new StringBuilder();
		whereCorse.append("id = " + _tid);
		String sql = String.format(this.ONE_SQL, viewName,whereCorse.toString());
		Query query= entityManager.createNativeQuery(sql);
		
		return  this.reflectClassedMap(e, getSingalQueryResult(query),null);
		
	}
	
	/**
	 * 查询单挑业务记录
	 * @param tid	业务唯一编码
	 * @param _repo	仓库类
	 * @return		业务对象实体类
	 */
	@SuppressWarnings("unchecked")
	protected T getOne(Long tid) {		
		
		if(tid==null){
			return null;
		}
		StringBuilder whereCorse = new StringBuilder();
		whereCorse.append("id = " + tid);
		String sql = String.format(this.ONE_SQL, this.tableName,whereCorse.toString());
		Query query= entityManager.createNativeQuery(sql);
		
		return (T) this.reflectObjectMap(clazz, getSingalQueryResult(query),null);
	}
	
	/**
	 * 查询单挑业务记录
	 * @param sql	查询sql	 * 
	 * @return		业务对象实体类
	 */
	@SuppressWarnings("unchecked")
	protected T getOneBySql(String sql) {		
		
		if(sql==null){
			return null;
		}		
		
		Query query = null;
		try {
			query = this.checkSqlDangerous(sql);			
		} catch (DangerousOperatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
		return (T) this.reflectObjectMap(clazz, getSingalQueryResult(query),null);
	}
	
	/**
	 * 查询单挑业务记录
	 * @param sql	查询sql	 * 
	 * @return		业务对象实体类
	 */
	@SuppressWarnings("unchecked")
	protected <E>E getOneBySql(String sql,Class clz) {		
		
		if(sql==null){
			return null;
		}		
		
		Query query = null;
		try {
			query = this.checkSqlDangerous(sql);			
		} catch (DangerousOperatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
		return (E) this.reflectObjectMap(clz, getSingalQueryResult(query),null);
	}
	
	
	
	/**
	 * 根据唯一标识查找实体对象
	 * @param identify
	 * @return
	 */
	protected List<T> getListByIdentify(@RequestParam(value="identify",required=false) String identify){		
		
		return getListByIdentify("identify",identify);
		
	}
	
	
	
	/**
	 * 根据唯一标识查找实体对象
	 * @param identify
	 * @return
	 */
	protected List<T> getListByIdentify(String identify,String value){
		
		
		
		StringBuilder sb = new StringBuilder();
		String sql = null;
		if(identify!=null){
			String whereCorse=String.format(sb.append("%1$s = \'%2$s\'").toString(),identify,value);
			sql = String.format(this.TWO_SQL, this.tableName,whereCorse,"sortedid asc");						
			return this.getAllList(sql);
		}
		return null;
		
	}
	
	/**
	 * 根据唯一标识查找实体对象
	 * @param identify
	 * @return
	 */
	protected List<T> getListByIdentifyByGet(String identify,String value){
		
		String _value= null;
		if(value!=null){
			
				_value = encodeStr(value);
			
		}
		StringBuilder sb = new StringBuilder();
		String sql = null;
		if(identify!=null){
			String whereCorse=String.format(sb.append("%1$s = \'%2$s\'").toString(),identify,_value);
			sql = String.format(this.TWO_SQL, this.tableName,whereCorse,"sortedid asc");			
			return this.getAllList(sql);
		}
		return null;
		
	}
	

	/**
	 * 根据唯一标识查找实体对象
	 * @param identify
	 * @return
	 */
	protected List<T> getListInIdentify(String identify,String value){
		
		StringBuilder sb = new StringBuilder();
		String sql = null;
		if(identify!=null){
			String whereCorse=String.format(sb.append("%1$s in ('%2$s')").toString(),identify,value);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);			
			return this.getAllList(sql);
		}
		return null;
		
	}
	/**
	 * 根据唯一标识查找实体对象
	 * @param identify
	 * @return
	 */
	protected T getOneByIdentify(@RequestParam(value="identify",required=false) String identify){		
		
		return getOneByIdentify("identify",identify);
		
	}
	/**
	 * 根据唯一标识查找实体对象
	 * @param identify
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected T getOneByIdentify(String identify,String value){
		
		String _identify = "identify";
		
		_identify = identify==null?_identify:identify;
		StringBuilder sb = new StringBuilder();
		String sql = null;
		
		if(identify!=null){
			String whereCorse=String.format(sb.append("%1$s = \'%2$s\'").toString(),_identify,value);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
			Query query= entityManager.createNativeQuery(sql);
			
			return (T) this.reflectObjectMap(clazz, getSingalQueryResult(query),null);
		}
		return null;
		
	}
	
	/**
	 * 根据唯一标识查找实体对象
	 * @param identify
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected T getOneByTable(String identify,String value){
		
		String _identify = "identify";
		
		_identify = identify==null?_identify:identify;
		StringBuilder sb = new StringBuilder();
		String sql = "select b.* ,T.TASK_DEF_KEY_ AS task_def_key from %1$s b left join act_ru_task t "
				+ " on b.flowInstId = t.PROC_INST_ID_ where %2$s";
		
		if(identify!=null){
			String whereCorse=String.format(sb.append("%1$s = \'%2$s\'").toString(),_identify,value);
//			sql = String.format(this.TW_SQL, this.moduleName,whereCorse);
			sql = String.format(sql, this.moduleName,whereCorse);
			Query query= entityManager.createNativeQuery(sql);
			
			return (T) this.reflectObjectMap(clazz, getSingalQueryResult(query),null);
		}
		return null;
		
	}
	
	/**
	 * 根据唯一标识查找实体对象
	 * @param identify
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected T getOneByIdentifyByGet(String identify,String value){
		
		String _identify = "identify";
		
		_identify = identify==null?_identify:identify;
		StringBuilder sb = new StringBuilder();
		String sql = null;
		
		String _value= null;
		if(value!=null){
			
				_value = encodeStr(value);
			
		}
		if(identify!=null){
			String whereCorse=String.format(sb.append("%1$s = \'%2$s\'").toString(),_identify,_value);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
			Query query= entityManager.createNativeQuery(sql);
			
			return (T) this.reflectObjectMap(clazz, getSingalQueryResult(query),null);
		}
		return null;
		
	}
	
	/**
	 * 集合对象查询
	 * @param query
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected List<LinkedHashMap> getQueryResult(Query query){
		
		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List<LinkedHashMap> lists = query.getResultList();
		return lists;
	}
	
	/**
	 * 集合对象查询
	 * @param query
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected HashMap<String,String> getSingleResult(Query query){
		
		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		Object obj = query.getSingleResult();
		
		HashMap map = null;
		if(obj!=null){
			map = (HashMap) obj;
		}else{
			map = new HashMap<String,String>();
		}
		return map;
	}
	
	/**
	 * 集合对象查询
	 * @param query
	 * @return
	 */
	@SuppressWarnings({ "unchecked"})
	protected List<T> getClassedQueryResult(Query query,Class<T> t){
		
		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(t));
		List<T> lists = query.getResultList();
		return lists;
	}
	
	
	
	
	
	/**
	 * json数据对象转换
	 * @param body json数据对象
	 * @param clazz 反序列化类实例
	 * @return 实例化的clazz对象
	 */
	protected T  bodyToObj (String body,Class<T> clazz){
		
		return  JsonUtil.bodyToObj(body, clazz);
	}
	
	/**
	 * 将map转换为bean
	 * @param map
	 * @param obj
	 * @return
	 */
	protected T transMap2Bean2(Map<String, Object> map, T obj) {  
        if (map == null || obj == null) {  
            return null;  
        }  
        try {  
            BeanUtils.populate(obj, map);  
        } catch (Exception e) {  
//            System.out.println("transMap2Bean2 Error " + e);  
        } 
        return obj;
    }  
	
	public String getTableName(){
		return this.tableName;
	}
	
	
	/*
	 * 反射获取对象所有定义的method
	 */
	protected void getEntityMethods(Object targetObj){
 
		
		
		_methodMap = new HashMap<String,Method>();
		
//		System.out.println("object type:" + targetObj.getClass());
//		System.out.println("object type:" );
		
		Method[] _method = targetObj.getClass().getMethods();
		if(_method!=null&&_method.length>0){
			for(int i=0;i<_method.length;i++){
				_methodMap.put(_method[i].getName().toUpperCase(), _method[i]);
//				System.out.println("Method: " + _method[i].getName() +"put in .");
			}
		}
		
		_method = targetObj.getClass().getDeclaredMethods();
		if(_method!=null&&_method.length>0){
			for(int i=0;i<_method.length;i++){
				_methodMap.put(_method[i].getName().toUpperCase(), _method[i]);
//				System.out.println("Method: " + _method[i].getName() +"put in .");
			}
		}
	}
	
	/*
	 * 通过反射将集合map对象映射到obj对象为泛型实体的List集合
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected List<T> reflectMaps(Class<T> obj,List<LinkedHashMap> maps){
		
//		List<T> objs = new ArrayList<T>();
//		if(maps!=null&&!maps.isEmpty()){
//			if(obj!=null){				
//				for(int i=0;i<maps.size();i++){
//					objs.add(this.reflectMap(obj, maps.get(i)));
//				}
//			}
//		}
		return (List<T>) reflectObjectMaps(obj, maps);
	}
	
	/*
	 * 通过反射将集合map对象映射到obj对象为泛型实体的List集合
	 */
	@SuppressWarnings("rawtypes")
	protected List<Object> reflectObjectMaps(Class<?> obj,List<LinkedHashMap> maps){
		
		List<Object> objs = new ArrayList<Object>();
		if(maps!=null&&!maps.isEmpty()){
			if(obj!=null){
				Object targetObj = null;
				try {
					targetObj = obj.newInstance();
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				getEntityMethods(targetObj);
				for(int i=0;i<maps.size();i++){
					objs.add(this.reflectObjectMap(obj, maps.get(i),_methodMap));
				}
			}
		}
		return objs;
	}
	
	/*
	 * 通过反射将集合map对象映射到obj对象为泛型实体的List集合
	 */
	@SuppressWarnings("rawtypes")
	protected <E>List<E> reflectClassedtMaps(Class<E> obj,List<LinkedHashMap> maps){
		
		List<E> objs = new ArrayList<E>();
		if(maps!=null&&!maps.isEmpty()){
			if(obj!=null){
				E targetObj = null;
				try {
					targetObj = obj.newInstance();
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				getEntityMethods(targetObj);
				for(int i=0;i<maps.size();i++){
					objs.add(this.reflectClassedMap(obj, maps.get(i),_methodMap));
				}
			}
		}
		return objs;
	}
	
	
	
	/*
	 * 通过反射将map中所有字段映射到对象obj中
	 */
	@SuppressWarnings("rawtypes")
	protected Object reflectObjectMap(Class<?> obj,Map map,Map<String,Method> methodMap){
		
		if((obj==null) || (map ==null)){
			return new Object();
		}
		Object targetObj = null;
		try {
			targetObj = obj.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(methodMap==null){
			
			getEntityMethods(targetObj);				
			
		}else{
			_methodMap = methodMap;
		}
		
		
		if(map!=null){
//			System.out.println(" field id: " + map.get("id"));
			for(Iterator ite= map.entrySet().iterator();ite.hasNext();){
				Map.Entry entry = (Map.Entry) ite.next();
//				System.out.println(" field name: " + entry.getKey());
				
				Object _entryValue = entry.getValue();
				
				_entryValue = _entryValue!=null?_entryValue.toString():null;
				setDataToField(targetObj,(String) entry.getKey(),_entryValue);
			}
		}
		return targetObj;
		
	}
	
	/*
	 * 通过反射将map中所有字段映射到对象obj中
	 */
	@SuppressWarnings("rawtypes")
	protected <E>E reflectClassedMap(Class<E> obj,Map map,Map<String,Method> methodMap){
		E targetObj = null;
		if((obj!=null) && (map !=null)){
			try {
				targetObj = obj.newInstance();
				
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			return targetObj;
		}
		
		
		if(methodMap==null){
			
			getEntityMethods(targetObj);				
			
		}else{
			_methodMap = methodMap;
		}
		
		
		if(map!=null){
//			System.out.println(" field id: " + map.get("id"));
			for(Iterator ite= map.entrySet().iterator();ite.hasNext();){
				Map.Entry entry = (Map.Entry) ite.next();
//				System.out.println(" field name: " + entry.getKey());
				
				Object _entryValue = entry.getValue();
				
				_entryValue = _entryValue!=null?_entryValue.toString():null;
				setDataToField(targetObj,(String) entry.getKey(),_entryValue);
			}
		}
		return targetObj;
		
	}
	
	/*
	 * 通过反射将map中所有字段映射到对象obj中
	 */
	@SuppressWarnings("rawtypes")
	protected <E>E reflectClassedMap(Class<E> obj,Map map){
		E targetObj = null;
		if((obj!=null) && (map !=null)){
			try {
				targetObj = obj.newInstance();
				
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			return targetObj;
		}		
			
		getEntityMethods(targetObj);	
		
		if(map!=null){
//			System.out.println(" field id: " + map.get("id"));
			for(Iterator ite= map.entrySet().iterator();ite.hasNext();){
				Map.Entry entry = (Map.Entry) ite.next();
//				System.out.println(" field name: " + entry.getKey());
				
				Object _entryValue = entry.getValue();
				
				_entryValue = _entryValue!=null?_entryValue.toString():null;
				setDataToField(targetObj,(String) entry.getKey(),_entryValue);
			}
		}
		return targetObj;
		
	}
	
	/**
	 * 通用监控数据查询方法
	 * @param startDate	开始时间
	 * @param endDate	结束时间
	 * @param sqls		查询语句
	 * @return
	 */
	protected List<T> monitorCountBase(String monitor_year_month,
			String startDate,String endDate,List<String> sqls){		
		
		//所有数据
		List<T> lists = new ArrayList<T>();
		
		if(startDate!=null && endDate!=null && sqls!=null && sqls.size()>0){
			for(int i=0;i<sqls.size();i++){
				String sql = sqls.get(i);
				
				sql = String.format(sql, monitor_year_month,startDate,endDate);
				List<T> allLists = getAllList(sql);
				if(allLists!=null && allLists.size()>0)
					lists.addAll(allLists);
			}
		}		
		return lists;
	}
	
	
	/**
	 * 通用基础数据查询方法
	 * @param startDate	开始时间
	 * @param endDate	结束时间
	 * @param sqls		查询语句
	 * @return
	 */
	protected List<T> countBase(
			String startDate,String endDate,List<String> sqls){		
		
		//所有数据
		List<T> lists = new ArrayList<T>();
		
		if(startDate!=null && endDate!=null && sqls!=null && sqls.size()>0){
			for(int i=0;i<sqls.size();i++){
				String sql = sqls.get(i);
				
				sql = String.format(sql,startDate,endDate);
				List<T> allLists = getAllList(sql);
				if(allLists!=null && allLists.size()>0)
					lists.addAll(allLists);
			}
		}		
		return lists;
	}
	
	/**
	 * 通用监控数据查询方法
	 * @param startDate	开始时间
	 * @param endDate	结束时间
	 * @param sqls		查询语句
	 * @return
	 */
	protected List<T> monitorCountBase(List<String> condition,
			List<String> sqls){		
		
		//所有数据
		List<T> lists = new ArrayList<T>();
		
		if(condition!=null && condition.size()>0){
			
			for(int i=0;i<sqls.size();i++){
				String sql = sqls.get(i);
				
				sql = String.format(sql, condition);
				List<T> allLists = getAllList(sql);
				if(allLists!=null && allLists.size()>0)
					lists.addAll(allLists);
			}
		}		
		return lists;
	}
	
	/**
	 * 获取监控开始和结束时间(yyyy-mm-dd)
	 * @param paramMap
	 * @return
	 */
	protected String[] getMonitorDate(Map<String,Object> paramMap){
		
		return DateUtil.getMapMonthDay(paramMap);
	}
	
	
	/*
	 * 将dataobj值赋给targetobj的fieldname字段
	 */
	private Object setDataToField(Object targetObj,String fieldName,Object dataObj){
		
		
		if(dataObj==null)
			return null;
		String methodName = "SET"+fieldName.toUpperCase();
		
		if(_methodMap.containsKey(methodName)){
			
			Method method = _methodMap.get(methodName);
			@SuppressWarnings("rawtypes")
			Class clazz = (method.getParameterTypes())[0];			
			
			String str = clazz.getName();				
			
			Object _paramObj = null;
			
			//处理str非null空值
			if(dataObj!=null){
				String dataObjValue = dataObj.toString().trim();			
				if(dataObjValue.compareTo("")==0)
					dataObj =null;
			}
			
			
			switch(str){
			
			case "java.lang.String"
				:_paramObj = dataObj;
				break;
			case "java.lang.Long"	
				:
					//_paramObj = dataObj!=null?Long.parseLong(dataObj.toString()):dataObj;
					_paramObj = dataObj!=null?LongUtil.getLongValue(dataObj.toString(),null):dataObj;
				break;
			case "java.lang.Integer"
				:
					//_paramObj = dataObj!=null?Integer.parseInt(dataObj.toString()):dataObj;
					_paramObj = dataObj!=null?LongUtil.getIntValue(dataObj.toString(),null):dataObj;
				break;
			case "double"	:
			case "java.lang.Double"	
				:
					try{_paramObj = dataObj!=null?Double.parseDouble(dataObj.toString()):dataObj;}
					catch(Exception e){_paramObj = null;}
				break;
			
			case "java.util.Date"
				:_paramObj = dataObj!=null?DateUtil.jsonStr2Date(dataObj.toString()):dataObj;
			};
			
			if(_paramObj!=null){
				try {						
					method.invoke(targetObj, _paramObj);				
				}  catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
//			System.out.println("method:" + method.getName() +" invokded.");
		}		
		return targetObj;
	}
	
	/*
	 * 根据配置文件定义查找用户唯一标识字段
	 */
	private String getFlowUserId(String userid){
		
		if(userid!=null){
			String userField = SysConfig.getConfig("user_identity_field");
			
			Users usr = SysConfig.getUsr(userid);
			if(usr!=null){
				//未配置，取用户identify
				userField = userField==null?usr.getIdentify():usr.getId().toString();
				return userField;
			}
		}
		return null;
	}
	
	/**
	 * 导出excel格式已完成数据集合
	 * @param body		参数
	 * @param response	servlet响应对象
	 * @param title		导出excel title
	 * @param sqlid		sql语句代码
	 */
	protected void exportExcel(ListDomain<T> domains,HttpServletResponse response,String title,String foot,String configStr){
		
		
		if(domains!=null){
			List<T> lists = domains.getRows();
			this.exportExcel(lists, response, title, foot, configStr);
		}
		
	}
	
	/**
	 * 导出excel格式已完成数据集合
	 * @param body		参数
	 * @param response	servlet响应对象
	 * @param title		导出excel title
	 * @param sqlid		sql语句代码
	 */
	protected void exportExcel(List<T> lists,HttpServletResponse response,String title,String foot,String configStr){
		
		
		
		ObjectMapper mapper = JsonUtil.getMapper();
		JavaType _javaType = mapper.getTypeFactory().constructCollectionType(List.class, ExportExcelDomain.class);

		List<ExportExcelDomain> list = null;
		try {
			list =  mapper.readValue(configStr, _javaType);
		}catch(Exception e){
			e.printStackTrace();
		}
		ExportUtil<T> eu = new ExportUtil<T>(title,foot,list,lists);
		try {
			eu.exportByDomain(response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
